package com.jy.admin.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.CeOrdersDao;
import com.jy.admin.db.dao.CePushLogDao;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.services.cashPocket.vo.ClOrderReceiveRequest;
import com.jy.admin.services.cashPocket.vo.RepaymentLinkVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 6:20 下午
 */
@Service
public abstract class BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseCrawlerService.class);
    @Autowired
    public OSSService ossService;

    @Autowired
    public CeOrdersDao ordersDao;

    @Autowired
    public CePushLogDao pushLogDao;

    @Autowired
    public ApolloConfigUtil apolloConfigUtil;

    public static final String collection_remove = "http://147.139.66.58:9108/collection/receive/remove";
    public static final String collection_update_remain_money = "http://147.139.66.58:9108/collection/receive/remainMoney/update";

    public abstract boolean hasLogin(CeAgentAccountEntity agentAccount);

    public abstract void refresh(CeAgentAccountEntity agentAccount);

    public abstract void updateOrderList(CeAgentAccountEntity agentAccount);

    public abstract void updateOrderDetailInfo(CeAgentAccountEntity agentAccount);


    public Map<String, String> getHeaders(CeAgentAccountEntity agentAccount) {
        String requestHeader = agentAccount.getRequestHeader();
        Map headers = Maps.newHashMap();
        if (StringUtils.isNotEmpty(requestHeader)) {
            Map<String, Any> stringAnyMap = JsonIterator.deserialize(requestHeader).asMap();
            stringAnyMap.keySet().forEach(k -> {
                headers.put(k, stringAnyMap.get(k).toString());
            });
        }

        return headers;
    }

    public abstract void compostCollectionData(CeAgentAccountEntity agentAccount);

    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== pushDataToCollection 开始推送订单到催收 ==,account:{}", agentAccount.getAccount());
        if (!apolloConfigUtil.getPushToCollectionSwitch()) {
            LOGGER.info("== pushDataToCollection 推送开关未打开 ==,account:{}", agentAccount.getAccount());
            return;
        }

        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.data_ready.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== pushDataToCollection 没有订单要推送 ==,account:{}", agentAccount.getAccount());
            return;
        }

        todayListBySyncStatusAndAgent.forEach(order -> {
            LOGGER.info("== pushDataToCollection 开始处理 ==,collectionNo:{}", order.getCollectionNo());
            CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
            if (pushLogEntity == null) {
                return;
            }

            if (pushLogEntity.getStatus() == 1) {
                LOGGER.info("== pushDataToCollection 开始推送到催收 ==,collectionNo:{}", order.getCollectionNo());
                ClOrderReceiveRequest request = JsonIterator.deserialize(pushLogEntity.getDetailInfo()).as(ClOrderReceiveRequest.class);
                try {
                    String pushToCollectionApi = apolloConfigUtil.getCollectionPushUrl();
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");

                    String requestBody = JSON.toJSONString(request);
                    String response = com.qianli.cashmama.trade.common.utils.HttpUtil.postPageBody(pushToCollectionApi, headers, requestBody);
                    LOGGER.info("pushToCollection推单给催收,api:{},request:{},response:{}", pushToCollectionApi, requestBody, JSON.toJSONString(response));

                    JSONObject responseObject = JSON.parseObject(response);
                    if (responseObject != null && responseObject.getIntValue("code") == 0) {
                        LOGGER.info("pushToCollection success,response:{}", JSON.toJSONString(response));
                        pushLogEntity.setStatus(2);
                        order.setSyncStatus(OrderSyncStatusEnum.push_success.getStatus());
                    } else {
                        pushLogEntity.setStatus(3);
                        order.setSyncStatus(OrderSyncStatusEnum.push_fail.getStatus());
                        LOGGER.error("pushToCollection 异常,response:{}", JSON.toJSONString(response));
                    }
                } catch (Exception e) {
                    pushLogEntity.setStatus(3);
                    order.setSyncStatus(OrderSyncStatusEnum.push_fail.getStatus());
                    LOGGER.error("逾期推送到催收失败,collectionDto:{}", JSON.toJSONString(request), e);
                }

                pushLogDao.updateByPrimaryKey(pushLogEntity);
                ordersDao.updateByPrimaryKey(order);
            }
        });


    }

    public abstract void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount);

    public abstract void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount);

    public abstract void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount);

    public abstract void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity);

    public abstract boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity);


    public abstract String updateRepaymentLink(String collectionNo, boolean isReduce);

    public abstract String updateExtensionRepaymentLink(String collectionNo,boolean isOpen);

    public abstract String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount);

    public abstract String queryPaymentOrderResult(String orderNo,String utr);

    public abstract String checkOrdersPaid(String orderNo);

    public String uploadContact(String orderNo, String content) {
        String smsFilePath = "cl/contact/contact_" + orderNo + "_" + System.currentTimeMillis() + ".json";
        return apolloConfigUtil.getOssBaseUrl() + "/" + ossService.uploadFile(smsFilePath, content);
    }


    public void updateRemainMoney(String collectionNo, String remainMoney) {

        if (!apolloConfigUtil.getMoneyUpdateSwitch()) {
            LOGGER.info("==更新remainMoney switch not open ==,collectNo:{},remainMoney:{}", collectionNo, remainMoney);
            return;
        }
        try {
            LOGGER.info("== 更新remainMoney ==,collectNo:{},remainMoney:{}", collectionNo, remainMoney);
            ordersDao.updateCollectionSystemRemainMoney(collectionNo, remainMoney);
        } catch (Exception e) {
            LOGGER.error("== 更新remainMoney error ==,collectNo:{}", collectionNo, e);
        }

    }

    public void updateMobile(String collectionNo, String mobile) {
        try {
            LOGGER.info("== 更新mobile ==,collectNo:{},mobile:{}", collectionNo, mobile);
            ordersDao.updateCollectionMobile(collectionNo, mobile);
        } catch (Exception e) {
            LOGGER.error("== 更新mobile error ==,collectNo:{}", collectionNo, e);
        }
    }

    public void updateName(String collectionNo, String name) {
        try {
            LOGGER.info("== 更新name ==,collectNo:{},name:{}", collectionNo, name);
            ordersDao.updateCollectionName(collectionNo, name);
        } catch (Exception e) {
            LOGGER.error("== 更新name error ==,collectNo:{}", collectionNo, e);
        }
    }

    public void updateAppName(String name,String originNo, String clientCode) {
        try {
            LOGGER.info("== 更新appName ==,orderNo:{},appName:{}", originNo, name);
            ordersDao.updateCollectionAppName(name, originNo,clientCode);
        } catch (Exception e) {
            LOGGER.error("== 更新appName error ==,orderNo:{}", originNo, e);
        }
    }

    public void updateContactUrl(String url,String originNo, String clientCode) {
        try {
            LOGGER.info("== 更新contactUrl ==,orderNo:{},url:{}", originNo, url);
            ordersDao.updateCollectionContactUrl(url, originNo,clientCode);
        } catch (Exception e) {
            LOGGER.error("== 更新contactUrl error ==,url:{}", originNo, e);
        }
    }

    public void updateImages(String originNo, String newImg, String clientCode) {

        LOGGER.info("== 开始更新图片 ==,originO:{},clientCode:{},newImg:{}", originNo, clientCode, newImg);
        try {
            ordersDao.updateImages(originNo, newImg, clientCode);
        } catch (Exception e) {
            LOGGER.error("== updateImages error ==,originNo:{},newImg:{}", originNo, newImg, e);
        }
    }

    public void updateAppLink(String originNo, String appLink, String clientCode) {

        try {
            ordersDao.updateAppLink(originNo, appLink, clientCode);
        } catch (Exception e) {
            LOGGER.error("== update app link error ==,originNo:{},appLink:{}", originNo, appLink, e);
        }
    }

}
